﻿using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Chess.Common.Network;
using Version = Chess.Common.Network.Version;

namespace Chess.Client
{
    public class Connection
    {
        private TcpClient _client { get; set; }
        private StreamReader _reader { get; set; }
        private StreamWriter _writer { get; set; }
        private Thread _worker { get; set; }
        private SerializedNetworkReader _serializedReader { get; set; }
        private SerializedNetworkWriter _serializedWriter { get; set; }
        private IPEndPoint _endPoint { get; set; }

        public delegate void ConnectedDelegate();
        public delegate void ErrorDelegate(ErrorType errorId);

        public ConnectedDelegate OnConnected;
        public ErrorDelegate OnError;

        public Connection()
        {
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            _endPoint = new IPEndPoint(ip, 1000);
            _client = new TcpClient();
            _reader = new StreamReader(_client.GetStream());
            _writer = new StreamWriter(_reader.BaseStream);
            _serializedReader = new SerializedNetworkReader(_reader);
            _serializedWriter = new SerializedNetworkWriter(_writer);
        }

        public void Connect()
        {
            _client.Connect(_endPoint);
            _worker = new Thread(NetworkLoop);
            _worker.Start();
        }

        public void Write(NetworkData data)
        {
            _serializedWriter.Write(data);
        }

        private void NetworkLoop()
        {
            Version version = new Version(0, 0, 1);
            HandshakePacket handshake = new HandshakePacket(version);
            Write(handshake);

            while (true)
            {
                NetworkData data = _serializedReader.Read();
            }
        }
    }
}
    